﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataParser;

namespace argusThreeAndAHalfMen
{
    public partial class frmBranchDetails : Form
    {
        //pointers
        public Branch branch; //pointer passes chosen branch from first form
        private Product selectedProduct;
        private Category selectedCategory;

        public frmBranchDetails(Branch branch)
        {

            InitializeComponent();
            this.branch = branch;
        }

        //GO TO HOME
        private void btnHome_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }

        //ADD PRODUCT
        private void btnAddProduct_Click(object sender, EventArgs e)
        {//create a temp add product form when add product is clicked.
            frmAddProduct tempAddProduct = new frmAddProduct(branch, this);
            tempAddProduct.Show();
        }

        //EDIT BRANCH CLICK EVENT
        private void btnEditBranch_Click(object sender, EventArgs e)
        {//create a temp edit branch form when edit branch is clicked.
            frmEditBranch tempEditBranch = new frmEditBranch(branch, this);
            tempEditBranch.Show();
        }

        //DELETE PRODUCT CLICK EVENT
        private void btnDeleteProduct_Click(object sender, EventArgs e)
        {//when button is clicked 
            bool productFound = false;
            Product removeProduct = null;
            Category removeProductFromCategory = null; 

            if (lstSearchProductResults.SelectedItem != null)
            {
                foreach (Category category in branch.Categories)
                {
                    foreach (Product product in category.ProductList)
                    {//if relevant object is selected in listbox, pointer is set for existing product object. Pointer also set to category in case category needs to be removed.
                        string thisProduct = lstSearchProductResults.Items[lstSearchProductResults.SelectedIndex].ToString(); //'thisProduct' is equal to the selected item in the search result.
                        int thisProductID = Convert.ToInt32(thisProduct.Substring(thisProduct.IndexOf(" (") + 2, 8)); //'thisProductID' is made equal to the object ID of the selected item in the listbox

                        if (thisProductID == product.ProductID)
                        {
                            productFound = true;
                            removeProduct = product;
                            removeProductFromCategory = category;
                        }
                    }
                }

                // Configure the message box to be displayed
                string messageBoxText = "Are you sure you want to delete this product?";
                string caption = "Delete Product";
                MessageBoxButtons button = MessageBoxButtons.YesNo;
                DialogResult result; 


                // Display message box
                result = MessageBox.Show(messageBoxText, caption, button);

                if (result == System.Windows.Forms.DialogResult.Yes)
                {//if user clicks yes, continue to removal of product and potential removal of category if category has no products in it after product removal
                    if (productFound == true)
                    {
                        removeProductFromCategory.ProductList.Remove(removeProduct);

                        if (removeProductFromCategory.ProductList.Count == 0)
                        {
                            branch.Categories.Remove(removeProductFromCategory);
                            cboCategories.Items.Remove(removeProductFromCategory.CategoryName);
                            cboCategories.SelectedIndex = 0;
                        }
                    }
                }
            }

            else if (lstSearchProductResults.SelectedItem == null) //if user hasn't selected a product(shouldn't be possible), show the following message in a messagebox.
                MessageBox.Show("Please select a product to delete from the list.", "No product selected");
            
            Parser.SaveBranchList("argus-BIG.txt"); //call save method

            //refresh branch page for continuity
            refreshSearchList(); 
            refreshProductDetails(); 
        }

        //EDIT PRODUCT CLICK EVENT
        private void btnEditProduct_Click(object sender, EventArgs e)
        {//if user has selected an item from the listbox, opens a window to edit the relevant product object and potential category mods
            if (lstSearchProductResults.SelectedItem != null)
            {
                foreach (Category category in branch.Categories)
                    foreach (Product product in category.ProductList)
                        if (product == selectedProduct)
                            selectedCategory = category; //set pointer to category in case it needs removing

                frmEditProduct tempEditProduct = new frmEditProduct(selectedProduct, this, selectedCategory, branch);
                tempEditProduct.Show();
            }

            else
                MessageBox.Show("Please select a product to edit from the list.", "No product selected"); //if no item is selected(shouldn't be possible), show this message to the user in a messagebox.
        }

        //ADD STOCK CLICK EVENT
        private void btnAddStock_Click(object sender, EventArgs e)
        {//adds stock to relevant listbox selection whilst if there is a valid number of stock to add
            try
            {
                if (Convert.ToInt32(txtAddStock.Text) > 0)
                {
                    // Configure the message box to be displayed
                    string messageBoxText = "Are you sure you want to add " + txtAddStock.Text + " stock to this product?";
                    string caption = "Adding Stock";
                    MessageBoxButtons button = MessageBoxButtons.YesNoCancel;
                    DialogResult result;

                    // Display message box
                    result = MessageBox.Show(messageBoxText, caption, button);

                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {//if user clicks yes, match selection to an existing product object and make changes to object
                        foreach (Category category in branch.Categories)
                            foreach (Product product in category.ProductList)
                            {
                                string thisProduct = lstSearchProductResults.Items[lstSearchProductResults.SelectedIndex].ToString();
                                int thisProductID = Convert.ToInt32(thisProduct.Substring(thisProduct.IndexOf(" (") + 2, 8));

                                if (product.ProductID == thisProductID)
                                {
                                    product.ProductStockLevel = product.ProductStockLevel + Convert.ToInt32(txtAddStock.Text);
                                }
                            }
                        Parser.SaveBranchList("argus-BIG.txt"); //call save method

                        //refresh details of currently selected product and set the stock textbox to 0
                        refreshProductDetails();
                        txtAddStock.Text = "";
                    }
                }

                else
                    MessageBox.Show("Please enter a number greater than 0.", "Invalid number"); //if the input is 0, show a message asking the user to enter a valid input.
            }
            catch
            {
                MessageBox.Show("Please enter a number.", "Invalid number"); //if an invalid input is inserted, show the messagebox.
            }
        }

        //BRANCH DETAILS LOAD EVENT
        private void frmBranchDetails_Load(object sender, EventArgs e)
        {//load event, contains all initialisation that needs to take place for form to work
            loadBranchDetails(); //load branch details of selected branch object ( from pointer 'branch' )
            cboCategories.Items.Add("All Categories"); //add 'All Categories' as the default option in the combobox.

            foreach (Category category in branch.Categories) 
            {//add all categories from branch object, add all products from all categories to listbox with name and ID
                cboCategories.Items.Add(category.CategoryName); 
                foreach (Product product in category.ProductList)
                    lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
                lstSearchProductResults.Sorted = true; //sort the products in alphabetical order.
            }
            cboCategories.Text = "All Categories"; //load the combobox again with all categories.
            resetListboxSelection();

            try
            {
                string chosenProduct = lstSearchProductResults.Items[0].ToString(); //initialises the product details as first in the list
                int productID = Convert.ToInt32(chosenProduct.Substring(chosenProduct.Length - 9, 7)); //initialises the product id as the first in the list.

                foreach (Category category in branch.Categories) //find category in branch categories.
                    foreach (Product product in category.ProductList) //find the product in the category productlist.
                        if (productID == product.ProductID) //if the product id is the same as in the product list for product id, run the following.
                        {
                            selectedProduct = product; //load the product.
                            imgProductImage.ImageLocation = product.ProductImagePath; //load the image.
                            lblProductID.Text = product.ProductID.ToString(); //load the id
                            txtProductName.Text = product.ProductName; //load the name
                            txtProductDescription.Text = product.ProductDesc; //load the description
                            lblProductPrice.Text = "£" + product.ProductPrice.ToString(); //load the price and add £ at the beginning.
                            lblStockLevel.Text = product.ProductStockLevel.ToString(); //load the stock level.
                        }
            }
            catch
            {
            }
        }

        //TEXT BOX TEXTCHANGED EVENT
        private void txtSearchProduct_TextChanged(object sender, EventArgs e)
        {
            refreshSearchList(); //refresh the search list
        }

        //TEXT BOX SEARCH CLICK EVENT
        private void txtSearchProduct_Click(object sender, EventArgs e)
        {//if default text is shown, clear textbox for user to enter new search. If search already exists, do nothing.
            if (txtSearchProduct.Text == "Type to search...")
                txtSearchProduct.Clear();
        }

        //TEXT BOX SEARCH ENTER EVENT
        private void txtSearchProduct_Enter(object sender, EventArgs e)
        {//if default text is shown, clear textbox for user to enter new search. If search already exists, do nothing.
            if (txtSearchProduct.Text == "Type to search...")
                txtSearchProduct.Clear();
        }

        //TEXT BOX SEARCH LEAVE EVENT
        private void txtSearchProduct_Leave(object sender, EventArgs e)
        {//if user has deleted their search value, searchbox resets to default. If not, search value will remain. Also checks combobox when refreshing.
            if (txtSearchProduct.Text == "")
            {
                txtSearchProduct.Text = "Type to search...";
                lstSearchProductResults.Items.Clear();

                if (cboCategories.Text == "All Categories") 
                    foreach (Category category in branch.Categories) 
                        foreach (Product product in category.ProductList) 
                            lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
                else if (cboCategories.Text != "All Categories")
                    foreach (Category category in branch.Categories)
                        if (cboCategories.Text == category.CategoryName)
                            foreach (Product product in category.ProductList)
                            {
                                lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");                                
                            }
            }
            lstSearchProductResults.Sorted = true;
        }

        //FORM BRANCH DETAILS FORMCLOSING EVENT
        private void frmBranchDetails_FormClosing(object sender, FormClosingEventArgs e)
        {//when closing form, refresh branchlist of home form, show home form
            frmHome.home.loadBranchList();
            frmHome.home.Show();
            this.Hide();
        }

        //REFRESH PRODUCT SEARCH LIST METHOD
        public void refreshSearchList()
        {//takes account of searchval and category whilst refreshing searchbox. breaks prevent infinite looping.
            lstSearchProductResults.Items.Clear();
            var searchVal = txtSearchProduct.Text;

            while (cboCategories.Text == "All Categories")
            {
                foreach (Category category in branch.Categories)
                    foreach (Product product in category.ProductList)
                    {
                        if (searchVal != "Type to search...")
                        {
                            if (product.ProductName.ToString().IndexOf(searchVal, StringComparison.OrdinalIgnoreCase) >= 0 || product.ProductID.ToString().IndexOf(searchVal, StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
                                lstSearchProductResults.Sorted = true;
                            }
                        }
                        else
                        {
                            lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
                            lstSearchProductResults.Sorted = true;
                        }
                    }
                break;
            }

            while (cboCategories.Text != "All Categories")
            {
                foreach (Category category in branch.Categories)
                    if (cboCategories.Text == category.CategoryName)
                        foreach (Product product in category.ProductList)
                        {
                            if (searchVal != "Type to search...")
                            {
                                if (product.ProductName.ToString().IndexOf(searchVal, StringComparison.OrdinalIgnoreCase) >= 0 || product.ProductID.ToString().IndexOf(searchVal, StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
                                    lstSearchProductResults.Sorted = true;
                                }
                            }
                            else
                            {
                                lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
                                lstSearchProductResults.Sorted = true;
                            }
                        }
                break;
            }

            while (txtSearchProduct.Text != "Type to search...")
            {
                if (lstSearchProductResults.Items.Count == 0 && txtSearchProduct.Text != null)
                {
                    lstSearchProductResults.Items.Add("No matches found...");
                }

                break;
            }
        }

        //
        public void loadBranchDetails()
        {//loads details of selected branch object
            lblBranchNicknameAndID.Text = branch.Nickname + " ( " + "ID: " + branch.BranchID.ToString() + " ) ";
            lblBA_NameAndStreet.Text = branch.StreetNumber + ", " + branch.StreetName;
            lblBA_CityCountyPostCode.Text = branch.City + ", " + branch.County + ", " + branch.Postcode;
        }

        //
        public void refreshProductDetails()
        {//refreshes product details pane using currently selected listbox item
            try
            {
                if (lstSearchProductResults.SelectedItem != null)
                {
                string chosenProduct = lstSearchProductResults.Items[lstSearchProductResults.SelectedIndex].ToString();
                int productID = Convert.ToInt32(chosenProduct.Substring(chosenProduct.Length - 9, 7));

                
                
                    foreach (Category category in branch.Categories)
                        foreach (Product product in category.ProductList)
                            if (productID == product.ProductID)
                            {
                                imgProductImage.ImageLocation = product.ProductImagePath;
                                lblProductID.Text = product.ProductID.ToString();
                                txtProductName.Text = product.ProductName;
                                txtProductDescription.Text = product.ProductDesc;
                                lblProductPrice.Text = "£" + product.ProductPrice.ToString();
                                lblStockLevel.Text = product.ProductStockLevel.ToString();

                                selectedProduct = product;
                            }
                }
            
                else if (lstSearchProductResults.SelectedItem == null)
                {
                    string chosenProduct = lstSearchProductResults.Items[0].ToString();
                    int productID = Convert.ToInt32(chosenProduct.Substring(chosenProduct.Length - 9, 7));

                    foreach (Category category in branch.Categories)
                        foreach (Product product in category.ProductList)
                            if (productID == product.ProductID)
                            {
                                imgProductImage.ImageLocation = product.ProductImagePath;
                                lblProductID.Text = product.ProductID.ToString();
                                txtProductName.Text = product.ProductName;
                                txtProductDescription.Text = product.ProductDesc;
                                lblProductPrice.Text = "£" + product.ProductPrice.ToString();
                                lblStockLevel.Text = product.ProductStockLevel.ToString();

                                selectedProduct = product;
                            }
                }
            }
            catch
            {
            }
        }

        //RESET LISTBOX SELECTION METHOD
        public void resetListboxSelection()
        {//resets listbox selection to first index
            lstSearchProductResults.SelectedIndex = 0;
        }

        //REFRESH CATEGORIES COMBO BOX
        public void refreshCategories()
        {//gets all categories from chosen branch object
            cboCategories.Items.Clear();
            cboCategories.Items.Add("All Categories");
            foreach (Category category in branch.Categories)
                cboCategories.Items.Add(category.CategoryName);
            cboCategories.Text = "All Categories";
        }

        //CATEGORIES COMBO BOX SELECTED INDEX CHANGED EVENT
        private void cboCategories_SelectedIndexChanged(object sender, EventArgs e)
        {//clear product listbox, refresh listbox with regard to search value and given category. If search value is null or default, all products in chosen category will appear.
            lstSearchProductResults.Items.Clear();
            if (cboCategories.Text == "All Categories")
                foreach (Category category in branch.Categories)
                    foreach (Product product in category.ProductList)
                        lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
            else
                foreach (Category category in branch.Categories)
                    if (cboCategories.Text == category.CategoryName)
                        foreach (Product product in category.ProductList)
                        {
                            lstSearchProductResults.Items.Add(product.ProductName + "  ( " + product.ProductID + " )");
                        }
        }
        
        //BTN SEARCH NEARBY CLICK EVENT
        private void btnSearchNearby_Click(object sender, EventArgs e)
        {//opens nearby stock form
            frmNearbyStock nearbyStock = new frmNearbyStock(branch, selectedProduct);
            nearbyStock.Show();
        }

        //LISTBOX PRODUCT SEARCH SELECTED INDEX CHANGED EVENT
        private void lstSearchProductResults_SelectedIndexChanged(object sender, EventArgs e)
        {//refreshes product details pane
            refreshProductDetails();
        }
    }
}
